package com.example.myapplication;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import org.osmdroid.api.IMapController;
import org.osmdroid.config.Configuration;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.ItemizedIconOverlay;
import org.osmdroid.views.overlay.ItemizedOverlayWithFocus;
import org.osmdroid.views.overlay.Marker;
import org.osmdroid.views.overlay.OverlayItem;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.osmdroid.views.overlay.Polyline;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity{
    private final int REQUEST_PERMISSIONS_REQUEST_CODE = 1;
    private MapView map = null;
    Float[][] point_arr = new Float[8000][2];
    String[] point_time =new String[8000];
    int poi_int=0;


    private ItemizedOverlayWithFocus<OverlayItem> mMyLocationOverlay;

    public void element() throws ParserConfigurationException {
        //导入gpx数据
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;
        builder = factory.newDocumentBuilder();
        Document d = null;
        try {
            d = builder.parse(getAssets().open("gpx.xml"));
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        NodeList sList = d.getElementsByTagName("RMC");
        double value;
        for (int i = 0; i < sList.getLength(); i++) {
            Node node = sList.item(i);
            NodeList subNodeList = node.getChildNodes();
            for (int j = 0; j < subNodeList.getLength(); j++) {
                Node subNode = subNodeList.item(j);
                if("timestamp".equals(subNode.getNodeName())){
                    String time = subNode.getFirstChild().getNodeValue().replace("[","").replace("]","");
                    point_time[poi_int]=time;
                }
                if("lat".equals(subNode.getNodeName())){
                    String lat = subNode.getFirstChild().getNodeValue().replace("[","").replace("]","");
                    value=(Double.valueOf(lat.toString())/100)+(Double.valueOf(lat.toString())%100)/60*0.0001;
                    BigDecimal b=new BigDecimal(value);
                    value=b.setScale(6,BigDecimal.ROUND_HALF_UP).doubleValue();
                    lat=String.valueOf(value);
                    point_arr[poi_int][0]=Float.parseFloat(lat);
                }
                if("lon".equals(subNode.getNodeName())){
                    String lon = subNode.getFirstChild().getNodeValue().replace("[","").replace("]","");
                    value=(Double.valueOf(lon.toString())/100)+(Double.valueOf(lon.toString())%100)/60*0.0001;
                    BigDecimal b=new BigDecimal(value);
                    value=b.setScale(6,BigDecimal.ROUND_HALF_UP).doubleValue();
                    lon=String.valueOf(value);
                    point_arr[poi_int][1]=Float.parseFloat(lon);
                    poi_int = poi_int + 1;
                }
            }
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Context ctx = getApplicationContext();
        Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx));

        //inflate and create the map
        setContentView(R.layout.activity_main);

        map = (MapView) findViewById(R.id.map);
        map.setTileSource(TileSourceFactory.MAPNIK);
        map.setBuiltInZoomControls(true);
        map.setMultiTouchControls(true);

        //确认一个默认视点，并在此上移动地图
        IMapController mapController = map.getController();
        mapController.setZoom(9.5);
        GeoPoint startPoint = new GeoPoint(30.51667, 114.31667);
        mapController.setCenter(startPoint);

        //导入gpx数据
        try {
            element();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        //创建点
        Marker startMarker = new Marker(map);
        Float aLat = point_arr[point_arr.length/2][0];
        Float aLon = point_arr[point_arr.length/2][1];
        GeoPoint point = new GeoPoint(aLat, aLon);
        startMarker.setPosition(point);
        startMarker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER);
        startMarker.setTitle(String.valueOf(point_time[point_arr.length/2]));
        map.getOverlays().add(startMarker);

        //创建线
        List<GeoPoint> geoPoints = new ArrayList<>();
        //add your points here
        for(int i = 0;i<point_arr.length/2;i++){
            Float aLat1 = point_arr[i][0];
            Float aLon1 = point_arr[i][1];
            geoPoints.add(new GeoPoint(aLat1, aLon1));
        }
//        geoPoints.add(new GeoPoint(30.51667, 114.31667));
//        geoPoints.add(new GeoPoint(30.51667, 114.32000));
        Polyline line = new Polyline();   //see note below!
        line.setPoints(geoPoints);
        line.setOnClickListener(new Polyline.OnClickListener() {
            @Override
            public boolean onClick(Polyline polyline, MapView mapView, GeoPoint eventPos) {
                Toast.makeText(mapView.getContext(), "polyline with " + polyline.getPoints().size() + "pts was tapped", Toast.LENGTH_LONG).show();
                return false;
            }
        });
        map.getOverlayManager().add(line);



        requestPermissionsIfNecessary(new String[] {
                // if you need to show the current location, uncomment the line below
                // Manifest.permission.ACCESS_FINE_LOCATION,
                // WRITE_EXTERNAL_STORAGE is required in order to show the map
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        });
    }



    @Override
    public void onResume() {
        super.onResume();
        //this will refresh the osmdroid configuration on resuming.
        //if you make changes to the configuration, use 
        //SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        //Configuration.getInstance().load(this, PreferenceManager.getDefaultSharedPreferences(this));
        map.onResume(); //needed for compass, my location overlays, v6.0.0 and up
    }

    @Override
    public void onPause() {
        super.onPause();
        //this will refresh the osmdroid configuration on resuming.
        //if you make changes to the configuration, use 
        //SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        //Configuration.getInstance().save(this, prefs);
        map.onPause();  //needed for compass, my location overlays, v6.0.0 and up
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        ArrayList<String> permissionsToRequest = new ArrayList<>();
        for (int i = 0; i < grantResults.length; i++) {
            permissionsToRequest.add(permissions[i]);
        }
        if (permissionsToRequest.size() > 0) {
            ActivityCompat.requestPermissions(
                    this,
                    permissionsToRequest.toArray(new String[0]),
                    REQUEST_PERMISSIONS_REQUEST_CODE);
        }
    }

    private void requestPermissionsIfNecessary(String[] permissions) {
        ArrayList<String> permissionsToRequest = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission)
                    != PackageManager.PERMISSION_GRANTED) {
                // Permission is not granted
                permissionsToRequest.add(permission);
            }
        }
        if (permissionsToRequest.size() > 0) {
            ActivityCompat.requestPermissions(
                    this,
                    permissionsToRequest.toArray(new String[0]),
                    REQUEST_PERMISSIONS_REQUEST_CODE);
        }
    }
}